﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamarinToolKit.Interfaces;
using XamarinToolKit.Model;

namespace XamarinToolKit.ViewModel
{
    public class MainDetailViewModel : ViewModelBase
    {
        private readonly IToolKitService service;

        public MainDetailViewModel()
        {
            AddCommand = new RelayCommand(Add);
            Messenger.Default.Register<string>(this, "SaveAccount", Save);
            service = DependencyService.Get<IToolKitService>();
        }

        private ToolKitInfo toolKitInfo;

        public ToolKitInfo ToolKitInfo
        {
            get { return toolKitInfo; }
            set { toolKitInfo = value; }
        }

        private ObservableCollection<ToolKitDetail> gridModelDetails;

        public ObservableCollection<ToolKitDetail> GridModelDetails
        {
            get { return gridModelDetails; }
            set
            {
                gridModelDetails = value;
                RaisePropertyChanged();
            }
        }


        private ToolKitDetail toolKitDetail;

        /// <summary>
        /// 绑定新增或者编辑的数据
        /// </summary>
        public ToolKitDetail ToolKitDetail
        {
            get { return toolKitDetail; }
            set
            {
                toolKitDetail = value;
                RaisePropertyChanged();
            }
        }


        public RelayCommand AddCommand { get; set; }

        void Add()
        {
            ToolKitDetail = new ToolKitDetail();
            ToolKitDetail.MasterId = ToolKitInfo.Master.Id;
            Messenger.Default.Send("新建账号", "OpenAddAccountView");
        }


        async void Save(string obj)
        {
            if (ToolKitDetail.Id > 0)
            {
                await service.UpdateToolKitDetail(ToolKitDetail);
            }
            else
            {
                await service.AddToolKitDetail(ToolKitDetail);
            }

            await UpdateGrids();
        }

        /// <summary>
        /// 根据主表Id刷新明细页面的数据
        /// </summary>
        /// <returns></returns>
        async Task UpdateGrids()
        {
            var details = await service.GetToolKitDetailsAsync(ToolKitInfo.Master.Id);
            GridModelDetails = new ObservableCollection<ToolKitDetail>();
            details?.ForEach(item =>
            {
                GridModelDetails.Add(item);
            });
        }
    }
}
